/**
* @file nowchat.dialog.js
* Copyright (c) Friends Group. All rights reserved.
* $Id$
*
*/

var ContextMenu = new Class
({
    options: 
    {
        id: 'contextMenu-' + $time(),
        imgsrc: '../images/',
        lostFocusHide: true,
        usefont: false,
        usesize: false,
        
        menuStyle: 
        {
            listStyle: 'none',
            padding: '1px',
            margin: '0px',
            backgroundColor: '#fff',
            border: '1px solid #999',
            width: '150px',
            fontFamily: 'tahoma',
            fontSize: '.8em'
        },
        itemStyle: 
        {
            margin: '0px',
            color: '#000',
            display: 'block',
            cursor: 'default',
            padding: '3px',
            border: '1px solid #fff',
            backgroundColor: 'transparent'
        },
        itemHoverStyle: 
        {
            border: '1px solid #0a246a',
            backgroundColor: '#b6bdd2'
        },
        
        items: [],
        
        customPosition: Class.empty,
        onMenuItem: Class.empty
    },
    
    initialize: function(options)
    {
        this.setOptions(options);
        
        this.menu = j$('<div class="ContextMenu" id="'+this.options.id+'"><ul></ul><div style="display:none;"></div></div>')
               .hide()
               .css({position:'absolute', zIndex:'50000'})
               .appendTo('body')
               .bind('click', function(e) 
                {
                    e.stopPropagation();
                });
        
        var fn = this;
        
        if(this.options.usefont)
        {
            j$.each(this.options.items, function(i, it)
            {
                fn.menu.find('ul').append('<li id="'+it.id+'" style="font-family:'+it.name+'">'+it.name+'</li>');
            });
        }
        else if(this.options.usesize)
        {
            j$.each(this.options.items, function(i, it)
            {
                fn.menu.find('ul').append('<li id="'+it.id+'" style="font-size:'+it.name+'">'+it.name+'</li>');
            });
        }
        else
        {
            j$.each(this.options.items, function(i, it)
            {
                fn.menu.find('ul').append('<li id="'+it.id+'"><img src="'+fn.options.imgsrc+it.imgsrc+'" alt="icon" />'+it.name+'</li>');
            });
        }
        
        j$('div#'+this.options.id+' li').click(function(ev)
        {
            fn.hide();
            fn.fireEvent('onMenuItem', [fn.menu.find('div').html(), ev.currentTarget.id]);
        });
    },
    
    addItem: function(item)
    {
        
    },
    
    hide: function()
    {
        this.menu.hide();
    },
    
    show: function(o, e)
    {
        j$('div.ContextMenu').hide();
        if(this.options.customPosition != undefined)
            e = this.options.customPosition(e);
        var content = this.menu.find('ul:first');
        var cur = this.options;
        content.css(cur.menuStyle).find('li').css(cur.itemStyle).hover(
          function() 
          {
            j$(this).css(cur.itemHoverStyle);
          },
          function()
          {
            j$(this).css(cur.itemStyle);
          }
        ).find('img').css({verticalAlign:'middle',paddingRight:'5px', marginTop:'-2px'});
        
        this.menu.css({'left':e.page.x,'top':e.page.y}).show();
        this.menu.find('div').html(o);
        
        if(this.options.lostFocusHide)
            j$(document).one('click', this.hide.bind(this));
    }
});
ContextMenu.implement(new Events, new Options);

var BaseClass = new Class
({
    
    getStatus: function(stas)
    {
        var bastatus = [{text: 'Online', cl: 'Online'}, {text: 'Offline', cl: 'Offline'}, 
                        {text: 'Available', cl:'Available'}, {text: 'Invisible', cl: 'Invisible'},
                        {text: 'Busy', cl: 'Busy'}, {text: 'Away', cl: 'Away'},
                        {text: 'Idle', cl: 'Idle'}, {text: 'Not at desk', cl: 'Idle'},
                        {text: 'Be right back', cl: 'Idle'}, {text: 'Stepped out', cl: 'Idle'}];
        
        for(var i = 0; i < bastatus.length; i++)
        {
            if(stas.toLowerCase() == bastatus[i].text.toLowerCase())
                return bastatus[i].cl;
        };
        
        return '';
    }
    
});

var BuddyDlgChat = BaseClass.extend
({
    options: 
    {
        title: 'Buddy chat',
        user1: {name: 'You', alias: '', status: '', avatar: '', id: ''},
        user2: {name: 'Your buddy', alias: '', status: '', avatar: '', id: ''},
        
        imgsrc: '../images/',
        buttonWidth: 22,
        buttonHeight: 22,
        // Events
        onTextareaEnter: Class.empty,
        onAddMessage: Class.empty,
        onCreate: Class.empty,
        onClose: Class.empty
    },

    initialize: function(options)
    {
        
        this.setOptions(options);
        
        if(this.options.user1.name.trim() == '')
            this.options.user1.name = this.options.user1.id;
        
        if(this.options.user1.alias.trim() == '')
            this.options.user1.alias = this.options.user1.name;
        
        if(this.options.user2.name.trim() == '')
            this.options.user2.name = this.options.user2.id;
        
        if(this.options.user2.alias.trim() == '')
            this.options.user2.alias = this.options.user2.name;
        
        var buddybar = '<div class="Header '+this.getStatus(this.options.user2.status)+'">'+
                            '<span class="Img"><div class="Img"/></span>'+
                            '<span class="Avatar"><img alt="Avatar của '+this.options.user2.alias+'" title="Avatar của '+this.options.user2.alias+'" src="'+this.options.user2.avatar+'" /></span>'+
                            '<span class="Name">'+this.options.user2.name+'</span>'+
                            '<span class="Status" title="'+this.options.user2.status+'">'+this.options.user2.status+'</span>'+
                        '</div>';
        
        var fontbar = '<div class="UIImFontbar"></div>';
        var textarea = '<div class="UIImMessage SeMessage"><textarea></textarea></div>';
        var status =  '<div class="UIImStatus"></div>';
        var messagelist = '<div class="UIImHistory ReMessage"></div>';
        
        var mainhtml = '<div id="'+this.options.id+'" class="flora" title="'+this.options.title+'">' + 
                            '<div class="UIDlgContentArea">' +
                            '</div>'+
                        '</div>';
        
        jQuery('body').append(mainhtml);
        
        this.dialog = j$('div#'+this.options.id);
        this.content = j$('div#'+this.options.id+' div.UIDlgContentArea');
        this.content.append(buddybar);
        this.content.append(messagelist);
        this.content.append(fontbar);
        this.content.append(textarea);
        this.content.append(status);
        
        this.messagelist = this.content.find('div.UIImHistory');
        this.fontbar = this.content.find('div.UIImFontbar');
        this.textarea = this.content.find('div.UIImMessage');
        this.status = this.content.find('div.UIImStatus');
        
        this.dialog = j$('div#'+this.options.id).dialog
        ({
            minHeight: 200, minWidth: 300, width: 450, height: 300,
            resize:function(ev, o)
            {
                fn._onResize(ev, o);
            },
            close: function(ev, ui)
            {
                ui.remove();
                j$('div#colorpicker-'+fn.options.user2.id).remove();
                fn.fireEvent('onClose', [ui, this]);
            }
        });
        
        var fn = this;
        this.textarea.keypress(function(ev)
        {
            if(ev.keyCode == 13) 
            {
                ev.preventDefault();
                fn.fireEvent("onTextareaEnter", (j$(this).find('textarea').val()));
                j$(this).find('textarea').val("");
            }
        });
        
        this.textarea.find('textarea').focus();
        var h = j$(this.dialog[0].parentNode.parentNode).height();
        var w = j$(this.dialog[0].parentNode.parentNode).width();
        
        this.content.height(h - 55);
        this.textarea.css
        ({
            width: w - 22 + 'px'
        });
        this.messagelist.css
        ({
            width: w - 25 + 'px',
            height: h - 178 + 'px'
        });
        this.fontbar.css
        ({
            top: h - 104 + 'px'
        });
        
        
        this.addFontbarButton({img: this.options.imgsrc + 'format-text-bold.png', title: 'Đậm', cla: 'Bold'});
        this.addFontbarButton({img: this.options.imgsrc + 'format-text-italic.png', title: 'Nghiêng', cla: 'Italic'});
        this.addFontbarButton({img: this.options.imgsrc + 'format-text-underline.png', title: 'Gạch chân', cla: 'Underline'});
        this.addFontbarButton({img: this.options.imgsrc + 'color-picker.png', title: 'Chọn màu', cla: 'Color'});
        this.addFontbarButton({img: this.options.imgsrc + 'font.png', title: 'Chọn font', cla: 'Font'});
        this.addFontbarButton({img: this.options.imgsrc + 'text-bigger.png', title: 'Chọn kích thước font', cla: 'FontSize'});
        
        this.fontbar.find('div.Bold').click(function()
        {
            fn._addTag('b');
        });
        this.fontbar.find('div.Italic').click(function()
        {
            fn._addTag('i');
        });
        this.fontbar.find('div.Underline').click(function()
        {
            fn._addTag('u');
        });
        
        new MooRainbow(j$(this.fontbar).find('div.Color')[0], 
        {
            id: 'colorpicker-'+this.options.user2.id, 'class': 'MooRainbow',
            imgPath: this.options.imgsrc + 'colorpicker/',
            onComplete: function(color)
            {
                fn._addTag('color', color.hex);
            }
        });
        
         this.options.comboSize = new ContextMenu
        ({
            id: 'myComboSize', usesize: true,
            items: [{name: '3em', id:'size3em'}, {name: '2.75em', id:'size275em'}, 
                {name: '2.5em', id:'size25em'}, {name: '2.25em', id:'size225em'},
                {name: '2em', id:'size2em'}, {name: '1.5em', id:'size15em'},
                {name: '1em', id:'size1em'}, {name: '0.9em', id:'size09em'},
                {name: '0.8em', id:'size08em'}, {name: '0.75em', id:'size075em'},
                {name: '0.5em',  id:'size05em'}],
            onMenuItem: function(o, ev)
                {
                if(ev == 'size3em')
                {
                    fn._addTag('size', '3');
                }
                else if(ev == 'size275em')
                {
                    fn._addTag('size', '2.75');
                }
                else if(ev == 'size25em')
                {
                    fn._addTag('size', '2.5');
                }
                else if(ev == 'size225em')
                {
                    fn._addTag('size', '2.25');
                }
                else if(ev == 'size2em')
                {
                    fn._addTag('size', '2');
                }
                else if(ev == 'size15em')
                {
                    fn._addTag('size', '1.5');
                }
                else if(ev == 'size1em')
                {
                    fn._addTag('size', '1');
                }
                else if(ev == 'size09em')
                {
                    fn._addTag('size', '0.9');
                }
                else if(ev == 'size08em')
                {
                    fn._addTag('size', '0.8');
                }
                else if(ev == 'size075em')
                {
                    fn._addTag('size', '0.75');
                }
                else if(ev == 'size05em')
                {
                    fn._addTag('size', '0.5');
                }
            },
            customPosition: function (e)
            {
                e.page.y -= 235;
                e.page.x += 20;
                return e;
            }
        });
        
        this.options.comboFont = new ContextMenu
        ({
            id: 'myComboFont', usefont: true,
            items: [{name: 'Arial', id:'font_arial'}, {name: 'Courier New', id:'fontCourierNew'}, 
                {name: 'Georgia', id:'fontGeorgia'}, {name: 'Lucida Sans', id:'fontLucidaSans'},
                {name: 'Lucida Sans Unicode', id:'fontLucidaSansUnicode'}, {name: 'MS Sans Serif', id:'fontMsSansSerif'},
                {name: 'Trebuchet MS', id:'fontTrebuchetMs'}, {name: 'Tahoma', id:'fontTahoma'},
                {name: 'Verdana',  id:'fontVerdana'}],
            onMenuItem: function(o, ev)
            {
                if(ev == 'font_arial')
                {
                    fn._addTag('font', 'Arial');
                }
                else if(ev == 'fontCourierNew')
                {
                    fn._addTag('font', 'Courier New');
                }
                else if(ev == 'fontGeorgia')
                {
                    fn._addTag('font', 'Georgia');
                }
                else if(ev == 'fontLucidaSans')
                {
                    fn._addTag('font', 'Lucida Sans');
                }
                else if(ev == 'fontLucidaSansUnicode')
                {
                    fn._addTag('font', 'Lucida Sans Unicode');
                }
                else if(ev == 'fontMsSansSerif')
                {
                    fn._addTag('font', 'MS Sans Serif');
                }
                else if(ev == 'fontTrebuchetMs')
                {
                    fn._addTag('font', 'Trebuchet MS');
                }
                else if(ev == 'fontTahoma')
                {
                    fn._addTag('font', 'Tahoma');
                }
                else if(ev == 'fontVerdana')
                {
                    fn._addTag('font', 'Verdana');
                }
            },
            customPosition: function (e)
            {
                e.page.y -= 240;
                e.page.x -= 15;
                return e;
            }
        });
        
        this.fontbar.find('div.Font')[0].addEvent('click', function(ev)
        {
            fn.options.comboFont.show('', ev);
            return false;
        });
        
        this.fontbar.find('div.FontSize')[0].addEvent('click', function(ev)
        {
            fn.options.comboSize.show('', ev);
            return false;
        });
        
        this.fireEvent('onCreate');
    },
    
    show: function()
    {
        j$(this.dialog).show();
    },
    
    hide: function()
    {
        j$(this.dialog).hide();
    },
    
    _addTag: function(tag, value)
    {
        var ntag = tag;
        if(value != undefined)
        {
            ntag = tag + '='+value;
        }
        var txt = j$(this.textarea).find('textarea');
        txt.val((txt.val()).substring(0, txt[0].selectionStart) + "["+ntag+"]" + (txt.val()).substring(txt[0].selectionStart, txt[0].selectionEnd) + "[/"+tag+"]" + (txt.val()).substring(txt[0].selectionEnd, txt[0].textLength));
        txt.focus();
    },
    
    active: function()
    {
        this.dialog.active();
    },
    
    setTitle: function(title)
    {
        this.dialog.attr('title', title);
    },
    
    setStatus: function(status)
    {
        this.status.text(status);
    },
    
    formatTime: function(time) 
    {
        return new Date(time).format('HH:MM:ss');
    },
    
    addMessage: function(message)
    {
        message = $extend({sender: this.options.user1.alias, time: $time(), ms: '', mst: 'You'}, message);
        if(message.sender != this.options.user1.alias)
            message.sender != this.options.user2.alias;
        
        if(message.ms != '')
        {
            var span = '<span class="'+message.mst+'">'+
                            '<span class="Time">['+this.formatTime(message.time)+'] <span class="Name">'+message.sender+'</span>: </span>'+
                            '<span class="Message">'+
                                   message.ms+
                            '</span><br/>'+
                        '</span>';
            
            this.messagelist.append(span);
            this.messagelist[0].scrollTop += 200000;
            this.fireEvent('onAddMessage', message);
        }
    },
    
    addToolbarButton: function(button){
        button = $extend({img: '', title: 'button'}, button);
        var button = '<div title="'+button.title+'" class="UIToolbarButton">'+
                            '<img width="'+this.options.buttonWidth+'" height="'+this.options.buttonHeight+'" title="'+button.title+'" src="'+button.img+'" />'+
                      '</div>'
        this.toolbar.append(button);
    },
    
    addFontbarButton: function(button)
    {
        button = $extend({img: '', title: 'button', cla: ''}, button);
        var button = '<div title="'+button.title+'" class="UIToolbarButton '+button.cla+'">'+
                            '<img width="'+this.options.buttonWidth+'" height="'+this.options.buttonHeight+'" title="'+button.title+'" src="'+button.img+'" />'+
                      '</div>'
        this.fontbar.append(button);
    },
    
    _onResize: function(ev, o)
    {
        this.fireEvent('onResize', [ev, o]);
        this.content.height(o.instance.size.height - 55);
        this.textarea.css
        ({
            width: o.instance.size.width - 22 + 'px'
        });
        this.messagelist.css
        ({
            width: o.instance.size.width - 25 + 'px',
            height: o.instance.size.height - 178+ 'px'
        });
        this.fontbar.css
        ({
            top: o.instance.size.height - 104 + 'px'
        });
    }
    
});
BuddyDlgChat.implement(new Events, new Options);

var BuddyDlgList = BaseClass.extend
({
    
    options: 
    {
        title: 'Now!chat messenger',
        imgsrc: '../images/',
        
        buttonWidth: 32,
        buttonHeight: 26,
        
        mst: 'Normal',
        owner: {name: '', alias: '', id: '', status: 'Available', avatar: ''},
        
        comboStatusContextMenu: Class.empty,
        groupContextMenu: Class.empty,
        buddyContextMenu: Class.empty,
        
        // Events
        onToolbarItem: Class.empty,
        onAddGroup: Class.empty,
        onAddGroupItem: Class.empty,
        onCreate: Class.empty,
        onStatusChanged: Class.empty
        
    },

    initialize: function(options)
    {
        
        this.setOptions(options);
        
        if(this.options.owner.name.trim() == '')
            this.options.owner.name = this.options.owner.id;
        
        var mainhtml = '<div id="'+this.options.id+'" class="flora" title="'+this.options.owner.alias+'">' + 
                            '<div class="UIToolbar"></div>'+
                            '<div class="DialogContent"></div>'+
                            '<div class="StatusSelect">'+
                                '<span class="Img"><div class="Img"/></span>'+
                                '<span class="Avatar"><img alt="Avatar của '+this.options.owner.alias+'" title="Avatar của '+this.options.owner.name+'" src="'+this.options.owner.avatar+'"/></span>'+
                                '<div class="Text"><span class="Name" title="'+this.options.owner.status+'">'+this.options.owner.status+'</span></div>'+
                            '</div>'+
                        '</div>';
        
        jQuery('body').append(mainhtml);
        
        this.dialog = j$('div#'+this.options.id);
        this.content = j$('div#'+this.options.id+' div.DialogContent');
        this.content.append('<div class="BuddyList"></div>');
        this.buddyList = this.content.find('div.BuddyList');
        this.toolbar = this.dialog.find('div.UIToolbar');
        this.statusBar = this.dialog.find('div.StatusSelect');
        
        this.dlgchat = new Hash();
        this.group = new Hash();
        this.menuevent = 'click';
        
        if(window.opera)
        {
            this.menuevent = 'click';
        }
        
        var fn = this;
        this.dialog.dialog
        ({
            minHeight: 350, minWidth: 200,
            position: [10, 30], height: 550, width: 250,
            resize:function(ev, o){
                fn._onResize(ev, o);
            }
        });
        
        
        this.statusBar.find('span.Name')[0].addEvent(this.menuevent, function(ev)
        {
            fn.options.comboStatusContextMenu.show(fn.statusBar[0].id, ev);
            return false;
        });
        
        this.options.comboStatusContextMenu = new ContextMenu
        ({
            id: 'myStatusMenu', imgsrc: this.options.imgsrc,
            items: [{name: 'Available', imgsrc: 'available.png', id:'statusAvailable'}, {name: 'Away', imgsrc: 'away.png', id:'statusAway'}, 
                {name: 'Be right back', imgsrc: 'away.png', id:'statusBeRightBack'}, {name: 'Busy', imgsrc: 'busy.png', id:'statusBusy'},
                {name: 'Not at desk', imgsrc: 'away.png', id:'statusNotAtDesk'}, {name: 'Stepped out', imgsrc: 'away.png', id:'statusSteppedOut'},
                {name: 'Invisible', imgsrc: 'invisible.png', id:'statusInvisible'}, {name: 'Offline', imgsrc: 'offline.png', id:'statusOffline'},
                {name: 'Custom', imgsrc: 'edit.png', id:'statusCustom'}],
            onMenuItem: function(o, ev)
                {
                if(ev == 'statusCustom')
                {
                    var htmml = '<div class="DlgCustomStatusContent flora Toolbox" title="Chọn status">'+
                                    '<p style="margin-bottom:10px;"><img alt="img" style="float:left;margin-right: 10px;" src="'+fn.options.imgsrc+'question.png"/><span>Nhập status bạn muốn hiển thị vào textbox</span></p>'+
                                    '<p><label for="statusName" style="width: auto;">Status:</label><input type="text" style="width:175px;height:20px;" id="statusName" /></p>'+
                                '</div>';
                    
                    j$(htmml).dialog
                    ({
                            id: 'DlgCustomStatus',
                            resizable: false, width: 250, height: 150,
                            buttons: {
                                'Chọn': function()
                                {
                                    var stname = j$('div.DlgCustomStatusContent').find('input#statusName').val();
                                    if(stname != '')
                                    {
                                        fn.setStatus(stname);
                                        fn.fireEvent('onStatusChanged', stname);
                                    }
                                    j$(this).dialog('close');
                                }
                            },
                            close: function(ev, ui)
                            {
                                ui.remove();
                            },
                            open: function()
                            {
                                j$('div.DlgCustomStatusContent').find('input#statusName').focus();
                            }
                    });
                }
                else if(ev == 'statusOffline')
                {
                    window.location.href = './logout.php';
                }
                else
                {
                    fn.setStatus(j$('#'+ev).text());
                    fn.fireEvent('onStatusChanged', j$('#'+ev).text());
                }
            },
            customPosition: function (e)
            {
                e.page.y -= 235;
                e.page.x -= 15;
                return e;
            }
        });
        
        var h = j$(this.dialog[0].parentNode.parentNode).height();
        var w = j$(this.dialog[0].parentNode.parentNode).width();
        
        this.content.height(h - 110);
        this.content.width(w);
        this.statusBar.css({top: h - 45 + 'px'});
        this.content.height(h - 110);
        if(window.opera)
            this.statusBar.find('span.Avatar').css({'margin-left': w-50 + 'px', 'margin-top': '-18px'});
        
        this.lastStatus = this.options.owner.status;
        this.setStatus(this.options.owner.status);
        
        this.addToolbarButton({img: this.options.imgsrc + 'addBuddy.gif', title: 'Thêm bạn', id: 'buttonAddBuddy'});
        this.addToolbarButton({img: this.options.imgsrc + 'removeBuddy.gif', title: 'Xóa bạn', id: 'buttonRemoveBuddy'});
        this.addToolbarButton({img: this.options.imgsrc + 'imbuddy.gif', title: 'Nhắn tin (đến bất cứ ai)', id: 'buttonSendBuddyMessage'});
        this.addToolbarButton({img: this.options.imgsrc + 'groupchat.gif', title: 'Tạo hoặc tham gia một phòng chat', id: 'buttonCreateRoom'});
        
        this.fireEvent('onCreate', this);
    },
    
    getMessageType: function()
    {
        return this.options.mst;
    },
    
    setMessageType: function(mst)
    {
        this.options.mst = mst;
    },
    
    setStatus: function(status)
    {
        this.statusBar.find('span.Name').html(status);
        this.statusBar.find('span.Name').attr('title', status);
        this.statusBar.removeClass(this.lastStatus);
        this.statusBar.addClass(this.getStatus(status));
        this.lastStatus = this.getStatus(status);
    },
    
    addToolbarButton: function(button)
    {
        button = $extend({img: '', title: 'button', id: ''}, button);
        this.toolbar.append('<div title="'+button.title+'" class="UIToolbarButton">'+
                                    '<img id="'+button.id+'" width="'+this.options.buttonWidth+'" height="'+this.options.buttonHeight+'" title="'+button.title+'" src="'+button.img+'" />'+
                              '</div>');
        var fn = this;
        this.toolbar.find('img#'+button.id).click(function(ev){
            fn.fireEvent('onToolbarItem', [ev.currentTarget.id]);
        });
    },
    
    show: function()
    {
        j$(this.dialog).show();
    },
    
    hide: function()
    {
        j$(this.dialog).hide();
    },
    
    setTitle: function(title)
    {
        this.dialog.attr('title', title);
    },
    
    updateDlgChatStatus: function(id, newStatus)
    {
        
        if(newStatus == 'Invisible')
            newStatus = 'Offline';
        
        id = id.substring(6);
        var children = j$('#'+this.options.owner.id+'-'+id+' .UIDlgContentArea .Header');
        var oldStatus = children.find('span.Status').text();
        
        children.find('span.Status').html(newStatus);
        children.find('span.Status').attr('title', newStatus);
        children.attr('class', '');
        children.addClass('Header');
        children.addClass(this.getStatus(newStatus));
        
        var buddyName = children.find('span.Name').text();
        if((newStatus == 'Offline') && (oldStatus != 'Offline' && oldStatus != 'Invisible'))
        {
            this.infoMessage(id, buddyName+' đã rời mạng');
            var dlg = this.dlgchat.get(this.options.owner.id+'-'+id);
            if(dlg != null)
                dlg.setStatus(buddyName+' không có trên mạng');
        }
        else if((oldStatus == 'Offline' || oldStatus == 'Invisible') && (newStatus != 'Offline'))
        {
            this.infoMessage(id, buddyName+' vừa mới lên mạng');
            var dlg = this.dlgchat.get(this.options.owner.id+'-'+id);
            if(dlg != null)
                dlg.setStatus(buddyName+' đang ở trên mạng');
        }
    },
    
    addGroup: function(name, id)
    {
        var ge = '<div id="'+id+'" class="UITree">'+
                    '<div class="Header Toggle ToggleOpen" title="Nhóm '+name+'">'+
                        '<span class="Img"><div class="Img"></div></span>'+
                        '<span class="Label">'+name+'</span>'+
                    '</div>'+
                    '<div class="Children"></div>'+
                  '</div';
        
        this.buddyList.append(ge);
        
        var op = this.buddyList.find('div#'+id);
        
        op.find('div.Img').click(function()
        {
            var main = j$(this.parentNode.parentNode.parentNode);
            var child = main.find('div.Children');
            var toggle = main.find('div.Toggle');
            if(child) child.toggle();
            toggle.toggleClass('ToggleOpen');
        });
        
        var fn = this;
        op.find('div.Toggle')[0].addEvent(this.menuevent, function(e) 
        {
            if(e.page.x > 40)
                fn.options.groupContextMenu.show(id.substring(6), e);
            return false;
        });
        
        this.group.set('div#'+id, op);
        this.fireEvent('onAddGroup', [name, id]);
    },
    
    addGroupItem: function(groupId, item)
    {
        item = $extend({id: '', name: '', alias: '', status: '', avatar: ''}, item);
        st = '';
        
        if(item.status == '')
        {
            st = 'style="margin-top:-5px;"';
        }
        else if(item.status == 'Invisible')
            (item.status = 'Offline');
        
        if(item.id == '')
        {
            item.id = $time();
            while($time() == item.id);
        }
        if(item.name.trim() == '')
            item.name = item.id.substring(6);
        
        if(item.alias.trim() == '')
            item.alias = item.name;
        
        var itemEle =  '<div class="UITree BuddyRow" id="'+item.id+'">'+
                            '<div class="Header '+this.getStatus(item.status)+'" title="'+item.alias+'">'+
                                '<span class="Img"><div class="Img"></div></span>'+
                                '<span class="Avatar"><img alt="Avatar của '+item.alias+'" title="Avatar của '+item.alias+'" src="'+item.avatar+'"/></span>'+
                                '<div class="Text" '+st+'>'+
                                    '<span class="Name">'+item.alias+'</span>'+
                                    '<span class="Status" title="'+item.status+'">'+item.status+'</span>'+
                                '</div>'+
                            '</div>'+
                        '</div>';
        
        var fn = this;
        
        var children = this.group.get('div#'+groupId).find('div.Children');
        children.append(itemEle);
        
        children.find('#'+item.id)[0].addEvent(this.menuevent, function(e) 
        {
            fn.options.buddyContextMenu.show(item.id.substring(6), e);
            return false;
        });
        
        children.find('#'+item.id)[0].addEvent('dblclick', function(e) 
        {
            fn.openDlgChat(item.id.substring(6));
            return false;
        });
        
        children.find('#'+item.id).attr('title', item.name);
        
    },
    
    addDlgChatMessage: function(dlgid, message, senderinfo)
    {
        if(senderinfo != undefined)
            senderinfo.status = Base64.decode(senderinfo.status);
        
        this.openDlgChat(dlgid, senderinfo);
        var chatId = this.options.owner.id+'-'+dlgid;
        var dlg = this.dlgchat.get(chatId);
        if(dlg != null)
            dlg.addMessage(message);
    },
    
    newMessage: function(mess)
    {
        var fn = this;
        j$.each(mess, function(i, ms)
        {
            if(ms.sender != '')
                fn.addDlgChatMessage(ms.sender, {sender: ms.sender, time: ms.time, ms: Base64.decode(ms.ms), mst: ms.mst}, ms.senderinfo);
        });
    },
    
    infoMessage: function(dlgid, ms)
    {
        this.addDlgChatMessage(dlgid, {sender: 'Tin nhắn từ Nowchat', time: $time(), ms: ms, mst: 'Info'});
    },
    
    warningMessage: function(dlgid, ms)
    {
        this.addDlgChatMessage(dlgid, {sender: this.options.owner.name, time: $time(), ms: ms, mst: 'Warning'});
    },
    
    alertMessage: function(dlgid, ms)
    {
        this.addDlgChatMessage(dlgid, {sender: this.options.owner.name, time: $time(), ms: ms, mst: 'Alert'});
    },
    
    openDlgChat: function(id, sender)
    {
        
        if(sender == undefined)
            sender = this._getCurrentUser('buddy-'+id);
        
        var fn = this;
        var chatId = this.options.owner.id+'-'+id;
        if(j$('#'+chatId).length == 0)
        {
            var dlg = new BuddyDlgChat
            ({
                id: chatId, imgsrc: this.options.imgsrc, title: sender.name,
                user1: this.options.owner, user2: sender,
                onClose: function(ui, o)
                {
                    fn.dlgchat.remove(chatId);
                },
                onTextareaEnter: function(text)
                {
                    fn.fireEvent("onDlgChatTextareaEnter", [id, text]);
                    return false;
                }
            })
            this.dlgchat.set(chatId, dlg);
            
            if(sender.status == 'Offline' || sender.status == 'Invisible')
            {
                this.infoMessage(id, sender.name+' hiện không có trên mạng, tin nhắn của bạn sẽ được gửi offline.');
                dlg.setStatus(sender.name+' không có trên mạng');
            }
            else
                dlg.setStatus(sender.name+' đang ở trên mạng');
            
        }
        else
        {
            j$('#'+chatId).dialog('activate');
        }
    },
    
    _getCurrentUser: function(id)
    {
        var item = j$('#'+id);
        if(item.length > 0)
        {
            return {
                name: item.find('span.Name').text(),
                alias: item.find('span.Name').text(),
                id: id,
                status: item.find('span.Status').text(),
                avatar: item.find('span.Avatar img').attr('src')
            }
        }
    },
    
    _onResize: function(ev, o)
    {
        this.fireEvent('onResize', [ev, o]);
        var w = o.instance.size.width;
        var h = o.instance.size.height;
        this.content.height(h - 110);
        this.content.width(w);
        this.statusBar.css({top: h - 45 + 'px'});
        if(window.opera)
            this.statusBar.find('span.Avatar').css({'margin-left': w-50 + 'px', 'margin-top': '-18px'});
    },
    
    buildBuddyList: function(buddyList)
    {
        this.buddyList.empty();
        var fn = this;
        j$.each(buddyList.groups, function(i, item)
        {
            if(item.id != '')
            {
                fn.addGroup(item.name, item.id);
                j$.each(item.items, function(ii, it)
                {
                    if(it.id != '')
                    {
                        it.status = Base64.decode(it.status);
                        fn.addGroupItem(item.id, it);
                        if(fn.dlgchat.get(fn.options.owner.id+'-'+it.id.substring(6)) != null)
                        {
                            fn.updateDlgChatStatus(it.id, it.status);
                        }
                    }
                })
            }
        });
        
    }
    
});
BuddyDlgList.implement(new Events, new Options);

